package com.example.myweather

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.example.myweather.adapter.ForecastAdapter
import com.example.myweather.pojo.Forecast
import com.example.myweather.pojo.Weather
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import java.net.URL

class MainActivity : AppCompatActivity() {

    companion object{
        private val DOMAIN = "http://t.weather.sojson.com/api/weather/city/"
        private val CITYCODE = "101180101" //郑州地区
        private val COMPLETEURL = "${DOMAIN}$CITYCODE"

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv.layoutManager = LinearLayoutManager(this)

        btn_request.setOnClickListener {
            doAsync {
                var requestWeather = requestWeather(COMPLETEURL)
                var forecast = requestWeather?.data?.forecast
                uiThread {
                    var adapter = ForecastAdapter(forecast){pos->toast("hello")}
                    rv.adapter = adapter
                    adapter.setOnItemClickListener { pos ->
                        toast("郑州${forecast!![pos].date}号当天的天气")
                    }
                }
            }
        }

    }

    fun requestWeather(urlpath: String): Weather? {
        var s = URL(urlpath).readText()
        Log.d("weather", s)
        return Gson().fromJson(s,Weather::class.java)
    }

}

